import mongoose, { Document, Schema } from 'mongoose';

export interface ILessonPlan extends Document {
  title: string;
  content: string;
  subject: string | mongoose.Types.ObjectId;
  grade: string | mongoose.Types.ObjectId;
  courseType: string | mongoose.Types.ObjectId;
  tags: string[];
  author: mongoose.Types.ObjectId;
  version: number;
  status: 'draft' | 'published' | 'archived';
  attachments: string[];
  views: number;
  likes: number;
  likedBy?: string[];
  comments: mongoose.Types.ObjectId[];
  isPublic: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const lessonPlanSchema = new Schema<ILessonPlan>({
  title: {
    type: String,
    required: true,
    trim: true,
    maxlength: 200,
  },
  content: {
    type: String,
    required: true,
  },
  subject: {
    type: Schema.Types.Mixed, // 支持字符串或ObjectId
    required: true,
  },
  grade: {
    type: Schema.Types.Mixed, // 支持字符串或ObjectId
    required: true,
  },
  courseType: {
    type: Schema.Types.Mixed, // 支持字符串或ObjectId
    required: true,
  },
  tags: [{
    type: String,
    trim: true,
  }],
  author: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
  version: {
    type: Number,
    default: 1,
  },
  status: {
    type: String,
    enum: ['draft', 'published', 'archived'],
    default: 'draft',
  },
  attachments: [{
    type: String,
  }],
  views: {
    type: Number,
    default: 0,
  },
  likes: {
    type: Number,
    default: 0,
  },
  likedBy: [{
    type: String,
    ref: 'User'
  }],
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'Comment',
  }],
  isPublic: {
    type: Boolean,
    default: true,
  },
}, {
  timestamps: true,
});

// 创建索引以提高查询性能
lessonPlanSchema.index({ title: 'text', content: 'text', tags: 'text' });
lessonPlanSchema.index({ subject: 1, grade: 1 });
lessonPlanSchema.index({ author: 1 });
lessonPlanSchema.index({ createdAt: -1 });

export const LessonPlan = mongoose.model<ILessonPlan>('LessonPlan', lessonPlanSchema);